//
//  RegexEx.swift
//  Risac
//
//  Created by remy on 2022/12/22.
//  Copyright © 2022 com.Risac. All rights reserved.
//

import Foundation

public struct Regex: ExpressibleByStringLiteral {
    private var expression: NSRegularExpression?
    
    public init(stringLiteral value: String) {
        self.expression = try? NSRegularExpression(pattern: value, options: [])
    }
    
    public func match(_ value: String) -> Bool {
        guard let expression = self.expression else { return false }
        return expression.numberOfMatches(in: value, options: [], range: value.nsRange) > 0
    }
    
    public func result(_ value: String) -> [NSTextCheckingResult] {
        guard let expression = self.expression else { return [] }
        return expression.matches(in: value, options: [], range: value.nsRange)
    }
    
    public func stringResult(_ value: String) -> [[String]] {
        self.result(value).map {
            var group: [String] = []
            for idx in 0..<$0.numberOfRanges {
                group.append(value[Range($0.range(at: idx))!])
            }
            return group
        }
    }
}

public func ~= (lhs: Regex, rhs: String) -> Bool {
    return lhs.match(rhs)
}

public func ~= (lhs: String, rhs: Regex) -> Bool {
    return rhs.match(lhs)
}
